from html_00_common_header import generate_common_header
from html_01_common_footer import generate_common_footer

import os
import json


def handle_fill_blank_path(self, parsed_path):
    try:
        try:
            index = 0 if parsed_path.query == "" else int(parsed_path.query)
        except (ValueError, TypeError):
            index = 0
        currentFile = self.questionFilesOfFill[index]
        # 获取文件的文件名排除后缀
        currentFileName = os.path.splitext(os.path.basename(currentFile))[0]
        # 计算上一题和下一题的Index
        preIndex = index - 1 if index > 0 else len(self.questionFilesOfFill) - 1
        nextIndex = index + 1 if index < len(self.questionFilesOfFill) - 1 else 0

        self.send_response(200)
        self.send_header("Content-type", "text/html; charset=utf-8")
        self.end_headers()
        self.wfile.write(
            (
                generate_common_header(f"{currentFileName}", "⌨")
                + get_button_bar(currentFileName, preIndex, nextIndex)
                + get_body(currentFile)
                + generate_common_footer()
            ).encode("utf-8")
        )
    except ValueError as e:
        self.send_error(400, "", str(e))
        return


def get_button_bar(currentFileName, preIndex, nextIndex):
    return (
        f"""
<div class='nav-container'>
    <a href="/fill_blank?{preIndex}" class="nav-button">上一题</a>
    <a href="/" class="nav-button">主页</a>
    <a href="/fill_blank?{nextIndex}" class="nav-button">下一题</a>
    <a href="/find_demo?{currentFileName}" class="nav-button" target="_blank">打开模拟</a>
    <a href="javascript:toggleEditable()" class="nav-button" id="toggleEditableButton">编辑->只读</a>
</div>
<div id="toggleAnswerButton" class="toggle-answer-button" onclick="toggleDisplay()">答</div>
"""
        + """
<script>
</script>
<style>
    .nav-container {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        background-color: white;
        padding: 4px 0;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        z-index: 1000;
    }
    body {
        padding-top: 60px;
    }
    .nav-button {
        display: inline-block;
        padding: 4px 8px;
        margin: 2px;
        background-color: #4CAF50;
        color: white;
        text-align: center;
        text-decoration: none;
        border-radius: 2px;
        transition: background-color 0.3s;
        font-size: smaller;
    }
    .nav-button:hover {
        background-color: #45a049;
    }
    .toggle-answer-button {
        position: fixed;
        right: 20px;
        bottom: 20px;
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background-color: #4CAF50;
        color: white;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        z-index: 1000;
        transition: background-color 0.3s;
    }
    .toggle-answer-button:hover {
        background-color: #45a049;
    }
</style>
"""
    )


def get_source(filePath):
    with open(filePath, "r", encoding="utf-8") as file:
        content = file.read()
    content = json.loads(content)
    # 遍历所有cells节点读取所有代码
    sources = []
    for cell in content["cells"]:
        if cell["cell_type"] == "code":
            sources += cell["source"]
    return "".join(sources)


def get_body(currentFile):
    return (
        f"""
<pre ondblclick="toggleDisplay()" style="" class="" contenteditable="true">
<code>{get_source(currentFile)}</code>
</pre>
<pre ondblclick="toggleDisplay()" style="display:none;" class="answer" contenteditable="true">
<code>{get_source(currentFile.replace('.ipynb','_答案.ipynb'))}</code>
</pre>
"""
        + """
<script>
    function toggleDisplay() {
        const questionnaire = document.querySelector('pre:not(.answer)');
        const answer = document.querySelector('pre.answer');
        if (questionnaire && answer) {
            if (answer.style.display !== 'block') {
                answer.style.display = 'block';
                questionnaire.style.display = 'none';
            } else {
                questionnaire.style.display = 'block';
                answer.style.display = 'none';
            }
        }
    }
    // 判断是否为移动设备
    function isMobileDevice() {
        return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    }
    // 根据设备类型设置默认可编辑状态
    document.addEventListener('DOMContentLoaded', function() {
        if(isMobileDevice())
            toggleEditable();
    });
    function toggleEditable() {
        const pres = document.querySelectorAll('pre');
        pres.forEach(pre => {
            pre.contentEditable = pre.contentEditable === 'true' ? 'false' : 'true';
        });
        const button = document.getElementById('toggleEditableButton');
        if (button) {
            button.textContent = button.textContent === '只读->编辑' ? '编辑->只读' : '只读->编辑';
        }
    }
</script>
"""
    )


def handle_find_demo_path(self, parsed_path):
    name = parsed_path.query
    fullPath = os.path.join(self.demo_path, name + ".html")
    if not os.path.exists(fullPath):
        self.send_error(404)
        return

    with open(fullPath, "r", encoding="utf-8") as file:
        content = file.read()

    self.send_response(200)
    self.send_header("Content-type", "text/html; charset=utf-8")
    self.end_headers()
    self.wfile.write(
        (
            generate_common_header(f"{name} - 模拟考试页面", "⌨")
            # 增加回退上一页按钮
            + f'<div><a href="javascript:navigation.back();">返回上一页</a></div>'
            + content
            + generate_common_footer()
        ).encode("utf-8")
    )
